from flask import Flask, request, jsonify, send_file
import os
from datetime import datetime
import shutil
import schedule
import time
from threading import Thread

app = Flask(__name__)

# 定义文件保存的根目录
BASE_DIR = "d://human/assets"

# 推流视频根目录
BASE_RESULT_DIR = "d://human"

# 确保根目录存在
if not os.path.exists(BASE_DIR):
    os.makedirs(BASE_DIR)

# 文件上传接口
@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400

    file = request.files['file']

    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    # 获取当前日期
    current_date = datetime.now().strftime("%Y%m%d")
    save_dir = os.path.join(BASE_DIR, current_date)

    # 确保日期目录存在
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    # 保存文件
    file_path = os.path.join(save_dir, file.filename)
    file.save(file_path)

    # 返回文件的URL
    file_url = f"http://127.0.0.1:5000/download/{current_date}/{file.filename}"
    return jsonify({"file_url": file_url}), 200

# 文件下载接口
@app.route('/download/<date>/<filename>', methods=['GET'])
def download_file(date, filename):
    file_path = os.path.join(BASE_DIR, date, filename)

    if not os.path.exists(file_path):
        return jsonify({"error": "File not found"}), 404

    return send_file(file_path)

# 本地视频查看
@app.route('/result/video', methods=['POST'])
def result_file():
    # file_path = os.path.join(BASE_RESULT_DIR, filepath)
    path = request.json.get("filepath")
    if not os.path.exists(path):
        return jsonify({"error": "File not found"}), 404

    return send_file(path)


# 定时任务：删除一天前的文件
def delete_old_files():
    current_date = datetime.now().strftime("%Y%m%d")
    for dir_name in os.listdir(BASE_DIR):
        if dir_name < current_date:
            dir_path = os.path.join(BASE_DIR, dir_name)
            shutil.rmtree(dir_path)
            print(f"Deleted directory: {dir_path}")

# 启动定时任务
def run_scheduler():
    schedule.every().day.at("00:00").do(delete_old_files)
    while True:
        schedule.run_pending()
        time.sleep(1)

if __name__ == '__main__':
    # 启动定时任务线程
    scheduler_thread = Thread(target=run_scheduler)
    scheduler_thread.daemon = True
    scheduler_thread.start()

    # 启动Flask应用
    app.run(debug=True)
